﻿using Fuse8.ContentManagementFramework.Administration.Controls;
using Fuse8.ContentManagementFramework.BizFacade.Services;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.Web.ApplicationRuntime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Telerik.Web.Mvc.UI;

namespace Fuse8.ContentManagementFramework.Administration.Controllers
{
    [CmsAuthorizeAttribute]
    public class CmsMediaForEditorController : EditorFileBrowserController
    {
        private readonly CmsMediaService _mediaService = new CmsMediaService();

        public override string[] ContentPaths
        {
            get
            {
                return new string[] { "/" };
            }
        }

        protected IEnumerable<CmsMedia> AllMedia
        {
            get
            {
                return _mediaService.FindAll();
            }
        }

        public override JsonResult Browse(string path)
        {
            do
            {
                path = path.Trim(new char[] { '/' });
            }
            while (path.Contains('/'));

            path = Server.UrlDecode(path);

            var result = new BrowseResult
            {
                ContentPaths = ContentPaths,
                Path = ""
            };

            var data = AllMedia;

            if ((data != null) && data.Any())
            {
                if (string.IsNullOrWhiteSpace(path))
                {
                    result.Directories = data.Select(
                        p => new DirectoryEntry
                        {
                            Name = p.FolderName
                        });
                    result.Files = new List<FileEntry>();
                    result.Path = path;
                }
                else
                {
                    var currentDirectory = data.FirstOrDefault(p => p.FolderName.Equals(path, StringComparison.OrdinalIgnoreCase));
                    if (currentDirectory != null)
                    {
                        var mediaContent = _mediaService.FindOne(currentDirectory.Id).MediaContents;

                        if ((mediaContent != null) && mediaContent.Any())
                        {
                            mediaContent = mediaContent.Where(p => p.MainFile.IsImage);
                        }

                        result.Files = (mediaContent != null) && mediaContent.Any() ?
                            mediaContent.Select(
                                p => new FileEntry
                                {
                                    Name = p.MainFile.FrontEndUrl.TrimStart(new char[] { '/' }),
                                    Size = p.MainFile.FileSize
                                }) :
                            new List<FileEntry>();
                    }

                    result.Directories = new List<DirectoryEntry>();
                    result.Path = result.Files.Count() == 0 ? path : string.Empty;
                }
            }

            return Json(result);
        }

        public override ActionResult Thumbnail(string path)
        {
            ActionResult result = null;

            if (!string.IsNullOrWhiteSpace(path))
            {
                var pathParts = path.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);

                if (pathParts.Length > 0)
                {
                    path = pathParts[pathParts.Length - 1].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries)[0];

                    int mediaFileId = 0;
                    if (int.TryParse(path, out mediaFileId))
                    {
                        result = new MediaFileHandler(HttpContext).GetMediaFile(mediaFileId, 96, 96, null);
                    }
                }
            }

            return result ?? new EmptyResult();
        }
    }
}